package com.tanhua.dubbo.api.mongo;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 今日佳人服务接口实现类
 */
@DubboService
@Slf4j
public class UserLikeApiImpl implements UserLikeApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private FriendApi friendApi;


    /**
     * 探花 - 右滑 flag:true 喜欢 false:不喜欢
     */
    @Override
    public boolean love(UserLike userLike) {
        log.debug("***********************************************************"+userLike.toString()+"**************************");
        //获取出值
        Boolean isLike = userLike.getIsLike();//是否喜欢
        Long likeUserId = userLike.getLikeUserId();
        Long userId = userLike.getUserId();
        long nowTime = System.currentTimeMillis();//系统数据

        //1.根据当前用户id和喜欢的用户id查询user_like记录是否存在
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        UserLike uk = mongoTemplate.findOne(query1, UserLike.class);
        //2.存在 更新记录
        if(uk != null){
            log.debug("*************更新**********************");
            Query query2  = new Query();
            query2.addCriteria(Criteria.where("id").is(uk.getId()));
            Update update = new Update();
            update.set("isLike",isLike);
            update.set("updated",nowTime);
            mongoTemplate.updateFirst(query2,update,UserLike.class);
        }else {
            log.debug("*************保存**********************");
            //3.不存在 保存记录
            userLike.setUpdated(nowTime);
            userLike.setCreated(nowTime);
            mongoTemplate.insert(userLike);
        }
        //4.如果是喜欢 判断对象是否喜欢登录用户
        if(isLike){//右滑
            log.debug("*************喜欢**********************");
            Query query3 = new Query();
            query3.addCriteria(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId).and("isLike").is(true));
            UserLike userLike2 = mongoTemplate.findOne(query3, UserLike.class);
            //5.将好友关系添加好友表（2条记录）
            if(userLike2 != null){
                log.debug("*************互相喜欢**********************");
                friendApi.addContacts(likeUserId,userId);
                return true;
            }
        }
        log.debug("*************不喜欢**********************");
        return false;
    }

    /**
     * 获取喜欢、互相喜欢、粉丝数量
     */
    @Override
    public Map<String, Long> getCounts(Long userId) {
        Map<String,Long> map = new HashMap<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        Long userLikeCount = mongoTemplate.count(query, UserLike.class);
        Long fans = mongoTemplate.count(new Query(Criteria.where("likeUserId").is(userId)), UserLike.class);
        Long friends =  mongoTemplate.count(query, Friend.class);

        map.put("loveCount",userLikeCount);
        map.put("fanCount",fans);
        map.put("eachLoveCount",friends);
        return map;
    }
    /**
     * 获取喜欢、互相喜欢、粉丝列表
     */
    @Override
    public PageResult findPageMyLoveOrFans(Long page, Long pageSize, Long userId , Integer type) {
        Query query = new Query();
        Long star = (page-1)*pageSize;
        String column = "userId";
        // 2.我的关注|3.喜欢
        if (type == 3){
            column = "likeUserId";
        }
        query.addCriteria(Criteria.where(column).is(userId).and("isLike").is(true));
        query.skip(star).limit(Math.toIntExact(pageSize));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        Long counts = Long.valueOf(userLikes.size());
        List<Long> collect = userLikes.stream().map(type == 2 ? UserLike::getLikeUserId : UserLike::getUserId).collect(Collectors.toList());
        PageResult pageResult = new PageResult(page, pageSize, counts, collect);
        return pageResult;
    }




}
